import subprocess
import os
import logging
from typing import Optional

# 配置日志
from utils.logger import logger

class DockerOperations:
    def __init__(self, org_name: str, registry: str = "registry.cn-hncs1.ctyun.cn"):
        self.org_name = org_name
        self.registry = registry
        self.login_info_file = "docker_login_info.txt"

    def run_command(self, command: str) -> bool:
        """执行 Docker 命令"""
        try:
            result = subprocess.run(command, shell=True, check=True, 
                                  capture_output=True, text=True)
            logger.info(f"执行命令: {command}")
            logger.info(f"输出: {result.stdout}")
            return True
        except subprocess.CalledProcessError as e:
            logger.error(f"命令执行失败: {e}")
            logger.error(f"错误输出: {e.stderr}")
            return False

    def get_login_command(self) -> Optional[str]:
        """从文件读取登录命令"""
        try:
            with open(self.login_info_file, "r") as f:
                for line in f:
                    if "docker login" in line:
                        return line.split(": ", 1)[1].strip()
            raise ValueError("未找到登录命令")
        except Exception as e:
            logger.error(f"读取登录信息失败: {e}")
            return None

    def push_image(self, image_name: str, tag: str = "latest") -> bool:
        """推送镜像到仓库"""
        login_cmd = self.get_login_command()
        if not login_cmd:
            return False

        commands = [
            login_cmd,
            f"docker pull {image_name}:{tag}",
            f"docker tag {image_name}:{tag} {self.registry}/{self.org_name}/{image_name}:{tag}",
            f"docker push {self.registry}/{self.org_name}/{image_name}:{tag}"
        ]

        for cmd in commands:
            if not self.run_command(cmd):
                logger.error("操作中断")
                return False
            logger.info("---")
        return True 